import preferences from '@ohos.data.preferences'


class PreferencesUtil {
  prefMap: Map<string, preferences.Preferences> = new Map()
  //异步
  loadPreference(context, name: string) {
    preferences.getPreferences(context, name)
      .then(pref => {
        console.log('testTag', `加载Preferences[${name}]成功`, JSON.stringify(pref))
        this.prefMap.set(name, pref)
      }).catch(reason => {
      console.log('testTag', `加载Preferences[${name}]失败`, JSON.stringify(reason))
    })
  }

  // //同步
  // async loadPreference2(context, name: string) {
  //   try {
  //     let pref = await preferences.getPreferences(context,name)
  //     console.log('testTag', `加载Preferences[${name}]成功`, JSON.stringify(pref))
  //     this.prefMap.set(name,pref)
  //   }catch (error){
  //     console.log('testTag', `加载Preferences[${name}]失败`, JSON.stringify(error))
  //   }
  // }
  //写入
  async putPreferenceValue(name: string, key: string, value: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      return
    }
    try {
      let pref = this.prefMap.get(name)
      //写入数据
      await pref.put(key, value)
      //刷新磁盘
      await pref.flush()
      console.log('testTag', `保存Preferences[${name}.${key} = ${value}]成功`)
    } catch (error) {
      console.log('testTag', `保存Preferences[${name}.${key}]失败`)
    }
  }

  async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType){
    if (!this.prefMap.has(name)) {
      return defaultValue
    }
    try {
      let pref = this.prefMap.get(name)
      //读取数据
      let value = await pref.get(key, defaultValue)
      console.log('testTag', `读取Preferences[${name}.${key} = ${value}]成功`)
      return value
    }catch (error){
      return defaultValue
      console.log('testTag', `读取Preferences[${name}.${key}]失败`)
    }
  }
  //删除
  async deletePreferenceValue(name: string, key: string){
    if (!this.prefMap.has(name)) {
      return
    }
    try {
      let pref = this.prefMap.get(name)
      pref.delete(key,(err)=>{
        if (err) {
          console.log('testTag', `删除Preferences[${err.code}.${err.message}]失败`)
        }
        console.log('testTag', `删除Preferences[${name}.${key}]成功`)
      })
    }catch (error){
      console.log('testTag', `删除Preferences[${name}.${key}]失败`)
    }
  }
}


const preferencesUtil = new PreferencesUtil()

export default preferencesUtil as PreferencesUtil